package com.eshop;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.PreparedStatement;

/**
 * Servlet implementation class PlaceOrder
 */
@WebServlet("/PlaceOrder")
public class PlaceOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PlaceOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection 			connection 	= null;
		Statement 			stmt 		= null;		
		PreparedStatement 	pst 		= null;
		
		ResultSet rs = null;
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		//write UI
		out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
		out.println("<html>");
		out.println("<head>");
		out.println("  <title>EShop</title>");
		out.println("  <style type=\"text/css\">");
		out.println("  body { font-family: Georgia, \"Times New Roman\",Times, serif; color: white; background-color: #272e34; background-image:url('images/background.jpg'); background-repeat:no-repeat;}");
		out.println("  h1.title   {margin-bottom:0px; margin-top:0px; font-family: Chiller, Geneva, Arial,SunSans-Regular, sans-serif; font-size:200px; color: #45c5f2; position: relative; left:500px;}");
		out.println("  h2.subtitle   {margin-bottom:0px; margin-top:0px; font-family: Georgia, Geneva, Arial,SunSans-Regular, sans-serif; font-size:20px; color: #45c5f2; position: relative; left:600px;}");
		out.println("  table.navbar { color: #45c5f2;left:600px; position:relative;}");
		out.println("  table.navbar td {  border:2px; border-style:solid; border-color:#45c5f2 #45c5f2;}");
		out.println("  table.cart{ color: #45c5f2; left:600px;  top:30px; position:relative;}");
		out.println("  a:link 	{ text-decoration:  none; color: #45c5f2  }");
		out.println("  a:visited { text-decoration:  none; color: #45c5f2  }");
		out.println(" </style>");
		out.println("</head>");
		out.println("<body>");
		
		out.println(" <h1 class=\"title\">EShop</h1>");
		
		out.println("<!-- Site navigation menu -->");
		out.println("<table class=\"navbar\">");
		out.println(" <td><a href=\"index.html\">Home page</a></td>");
		out.println(" <td><a href=\"Products.html\">Products</a></td>");
		out.println(" <td><a href=\"ShoppingCart.html\">Shopping Cart</a></td>");
		out.println(" <td><a href=\"Register.html\">Register</a></td>");
		out.println(" </table>");
		
		// Get the current session object, create one if necessary.
		HttpSession session = request.getSession();
		
		Enumeration attributeNames = session.getAttributeNames();
		Object obj = session.getAttribute( "mySession" );
		
		int totalCost = 0;
		
		try{
			// Load (and therefore register) the Oracle Driver
			Class.forName("com.mysql.jdbc.Driver");
			// Get a Connection to the database
			connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/eshop", "root", "admin");
			// Create a Statement object
			stmt = connection.createStatement();
			
			// Print the current cart items.
			
			if (attributeNames == null) 
			{
				out.println("<B>None</B>");
			}
			else 
			{
				//we check if there is a customer with this username
				String usrname 	= request.getParameter("username");
				if(usrname != null)
				{
					rs = stmt.executeQuery("SELECT FirstName FROM customer WHERE username='"+ usrname + "'");
					if(!rs.next())
					{
						//have to register first
						getServletContext().getRequestDispatcher("/Register.html").forward(request,response);
						
					}
					else
					{
						//first we have to insert a new row in the orders table
						long timeS = System.currentTimeMillis();
						
						pst = (PreparedStatement) connection.prepareStatement("INSERT INTO customerorders ( Username, OrderTimestamp) VALUES (?,?)");
						pst.setString(1, usrname);
						pst.setString(2, String.valueOf(timeS));
						int numRowsChanged = pst.executeUpdate();
						pst.close();
						
						//take the order ID
						int orderId = 0;		
						rs = stmt.executeQuery("SELECT OrderID FROM customerorders WHERE OrderTimestamp = " + String.valueOf(timeS));
						if(rs.next())
						{
							orderId = rs.getInt("OrderID");
						}
						//rs = stmt.executeQuery("SELECT OrderID FROM order WHERE Year='" + sYear + "' AND Month='" + sMonth + "' AND Day='" + sDay + "' AND Hour='" + sHour + "' AND Minutes='" + sMinutes + "' AND Seconds='" + sSeconds +"'");
						
						
						//iterate in the shopping cart and insert into ordered products label
						while( attributeNames.hasMoreElements() ) 
						{
							String attributeName = (String) attributeNames.nextElement();
							obj = session.getAttribute( attributeName );
							
							// Execute an SQL query, get a ResultSet
							pst = (PreparedStatement) connection.prepareStatement("INSERT INTO productorders (OrderID, ProductID, Quantity) VALUES (?,?,?)");
							pst.setInt(1, orderId);
							pst.setString(2, attributeName);
							pst.setString(3, obj.toString());
							pst.executeUpdate();
							pst.close();
						}
						
						session.invalidate(); 
					}
				}
			}
		}
		catch(ClassNotFoundException e) {
			out.println("Couldn't load database driver: " + e.getMessage());
		}
		catch(SQLException e) {
			out.println("SQLException caught: " + e.getMessage());
		}
		finally {
			// Always close the database connection.
		try {
		if (connection != null) connection.close();
		}
		catch (SQLException ignored) { }
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int i = 0;
		i++;
	}

}
